<template>
  <view class="rank-box">
    <view class="rank-text">
      您现在处于
      <text class="text">{{ getStage() }}</text>
      阶段
      <view class="rank-score"
        >目前您的分数为
        <text class="text">{{ totalScore }}</text>
      </view>
    </view>
    <view class="rank-warp">
      <canvas
        ref="chartsCanvas"
        :id="id"
        :class="testCharts"
        :canvas-id="id"
        type="2d"
        :style="{ width: width + 'rpx', height: height + 'rpx' }"
      />
    </view>
    <view class="rank-bg" :style="{ height: height + 'rpx' }">
      <view
        class="rank-item"
        v-for="(item, index) in honorScoreList"
        :key="item.id"
        :style="{ width: 100 / honorScoreList.length + '%' }"
      >
        <!-- count(index) -->
        <text class="name">{{ item.stageName }}</text>
        <text class="score">{{ item.score }}</text>
      </view>
      <view class="rank-item rank-end">
        <text class="score">40000</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import {
  onMounted,
  ref,
  getCurrentInstance,
  defineProps,
  watch,
  computed,
} from "vue";
// #ifdef MP-WEIXIN
import uChartsByWeiXin from "@/package_honour/pages/honour/utils/uCharts/weixin.js";
// #endif

// #ifdef H5
import uChartsByH5 from "@/package_honour/pages/honour/utils/uCharts/h5.js";
// #endif
import { px2Rpx } from "@/utils/utils";

const { proxy } = getCurrentInstance();
const props = defineProps({
  width: {
    type: Number,
    default: 750,
  },
  height: {
    type: Number,
    default: 500,
  },
  rankClassify: {
    type: Array,
    default: [],
  },
  totalScore: {
    type: Number,
    default: 0,
  },
  honorScoreList: {
    type: Array,
    default: [],
  },
  id: {
    type: String,
  },
});

const chartsCanvas = ref(null);
const cWidth = ref(0);
const cHeight = ref(0);
const pixelRatio = ref(0);
const testCharts = ref(["default-class"]);
let uChartsInstance = {};

watch(
  () => props.totalScore,
  () => {
    console.log("props.totalScore", props.totalScore);

    /* #ifdef MP-WEIXIN */
    drawChartInWeiXin();
    /* #endif */

    /* #ifdef H5 */
    drawChartInH5();
    /* #endif */
  }
);
watch(
  () => props.honorScoreList,
  () => {
    console.log("props.honorScoreList", props.honorScoreList);
    categories.value = generateCategories();
    /* #ifdef MP-WEIXIN */
    drawChartInWeiXin();
    /* #endif */

    /* #ifdef H5 */
    drawChartInH5();
    /* #endif */
  }
);
const rankClassify = computed(() =>
  props.rankClassify.map((rank) => rank.score)
);
function count(index) {
  if (index < props.honorScoreList.length - 1) {
    let num =
      ((props.honorScoreList[index + 1].score -
        props.honorScoreList[index].score) /
        40000) *
      100;
    return num + "%";
  } else {
    let num = ((40000 - props.honorScoreList[index].score) / 40000) * 100;
    return num + "%";
  }
}
function added() {
  if (props.totalScore !== 0) {
    if (props.totalScore <= 3000) {
      return props.totalScore + 2500;
    } else if (props.totalScore <= 7000) {
      if (props.totalScore <= 5000) {
        return props.totalScore + 3000;
      } else {
        return props.totalScore + 4000;
      }
    } else if (props.totalScore <= 13000) {
      return props.totalScore + 3800;
    } else if (props.totalScore <= 20000) {
      if (props.totalScore - 13000 < 1000) {
        return props.totalScore + 3600;
      } else {
        return props.totalScore + 1900;
      }
    } else if (props.totalScore > 20000) {
      if (props.totalScore - 20000 < 10000) {
        return props.totalScore - 1500;
      } else {
        return props.totalScore - 5500;
      }
    }
  }
}
const categories = ref([]); // 使用函数生成足够多的数据点
const drawChartInWeiXin = () => {
  let num = 40000;
  const query = uni.createSelectorQuery().in(proxy);
  query
    .select("#" + props.id)
    .fields({ node: true, size: true })
    .exec((res) => {
      if (res[0]) {
        const data = {
          categories: categories.value,
          series: [
            {
              name: "曲线1",
              data: generatePowerData(num, categories.value, 20), // 添加起始 y 值参数
              color: "#eee",
            },
            {
              name: "曲线2",
              data: generatePowerData(added(), categories.value, 20), // 添加起始 y 值参数
              color: "#FF7C00",
            },
          ],
        };
        const canvas = res[0].node;
        const ctx = canvas.getContext("2d");
        canvas.width = px2Rpx(res[0].width);
        canvas.height = px2Rpx(res[0].height);
        uChartsInstance[props.id] = new uChartsByWeiXin({
          type: "line",
          context: ctx,
          width: canvas?.width,
          height: canvas?.height,
          dataLabel: false,
          dataPointShape: false,
          categories: data?.categories,
          series: data?.series,
          legend: {
            show: false,
          },
          xAxis: {
            type: "grid",
            gridType: "dash",
            boundaryGap: true, // 根据需要设置，如果不需要两端留白则设为 false
            disableGrid: true, // 禁用默认的网格线
            min: 0,
            max: num,
            axisLine: false,
            formatter: (value) => {
              if (rankClassify.value.includes(value)) {
                return value;
              } else {
                return "";
              }
            },
          },
          yAxis: {
            disabled: true,
            disableGrid: true,
          },
          extra: {
            line: {
              type: "curve",
            },
            lineStyle: "curve", // 启用平滑曲线
            lineClassify: rankClassify.value,
          },
        });
      }
    });
};

const drawChartInH5 = () => {
  let num = 40000;
  const ctx = uni.createCanvasContext(props.id);
  const query = uni.createSelectorQuery().in(proxy);
  let canvasWidth;
  let canvasHeight;
  query
    .select("#" + props.id)
    .fields({ node: true, size: true })
    .exec((res) => {
      if (res[0]) {
        canvasWidth = res[0].width;
        canvasHeight = res[0].height;
      }
    });
  const data = {
    categories: categories.value,
    series: [
      {
        name: "曲线1",
        data: generatePowerData(num, categories.value, 20), // 添加起始 y 值参数
        color: "#eee",
        legend: false,
      },
      {
        name: "曲线2",
        data: generatePowerData(added(), categories.value, 20), // 添加起始 y 值参数
        color: "#FF7C00",
        legend: false,
      },
    ],
  };
  new uChartsByH5({
    // canvasId: 'chartCanvas',
    type: "line",
    context: ctx,
    dataLabel: false,
    dataPointShape: false,
    legend: {
      show: false,
    },
    categories: data.categories,
    series: data.series,
    xAxis: {
      type: "grid",
      boundaryGap: true, // 根据需要设置，如果不需要两端留白则设为 false
      disableGrid: true, // 禁用默认的网格线
      axisLine: false,
      formatter: (value) => {
        if (rankClassify.value.includes(value)) {
          return value;
        } else {
          return "";
        }
      },
    },
    yAxis: {
      disabled: true,
      disableGrid: true,
    },

    width: canvasWidth - 5 || cWidth.value,
    height: canvasHeight || cHeight.value,
    extra: {
      line: {
        type: "curve",
      },
      lineStyle: "curve", // 启用平滑曲线
      lineClassify: rankClassify.value,
    },
  });
};

onMounted(() => {
  cWidth.value = uni.upx2px(props.width);
  cHeight.value = uni.upx2px(props.height);
  pixelRatio.value = uni.getSystemInfoSync().pixelRatio;
  // if (JSON.stringify(props.honorScoreList) !== "[]") {
  //   categories.value = generateCategories()
  //   /* #ifdef MP-WEIXIN */
  //   drawChartInWeiXin();
  //   /* #endif */

  //   /* #ifdef H5 */
  //   drawChartInH5();
  //   /* #endif */
  // }
});

function generatePowerData(maxX, categories, startY = 20) {
  return categories.map((x) =>
    x <= maxX ? Math.max(Math.pow(x, 2), startY) : null
  );
}

function generateCategories() {
  console.log("generateCategories", props.honorScoreList);

  let points = [];
  for (
    // let x = 1;
    let x = 100;
    x <
    props.honorScoreList[props.honorScoreList.length - 1]?.score +
      (props.honorScoreList[props.honorScoreList.length - 1]?.score -
        props.honorScoreList[props.honorScoreList.length - 2]?.score);
    x += 100
  ) {
    points.push(x);
  }
  return points;
}

const getStage = () => {
  const score = props.totalScore;
  if (score >= 0 && score <= 3000) return "启程";
  else if (score >= 3001 && score <= 7000) return "进阶";
  else if (score >= 7001 && score <= 13000) return "优秀";
  else if (score >= 13001 && score <= 20000) return "卓越";
  else return "顶尖";
};
</script>
<style lang="less" scoped>
.rank-box {
  .rank-text {
    color: @color-black;
    font-family: "ali-m";
    margin-bottom: 30rpx;
    font-size: @font-size-31;
    margin-left: 20rpx;

    .text {
      font-size: @font-size-39;
      color: @color-orange;
    }

    .rank-score {
      margin-top: 10rpx;
      font-size: 20rpx;
      color: @color-label;
      font-family: "ali";

      .text {
        font-size: 25rpx;
        font-family: "ali-m";
      }
    }
  }

  .rank-warp {
    position: absolute;
    z-index: 1;
  }
}

.rank-bg {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10%;
  position: relative;
  padding: 0 10rpx 0 20rpx;

  .rank-item {
    position: relative;
    border-left: 1px dashed #d0d0d0;

    &:last-child {
      border-right: 1px dashed #d0d0d0;
    }

    .name {
      position: absolute;
      bottom: -10rpx;
      left: 50%;
      transform: translateX(-50%);
      font-size: 25rpx;
      color: @color-label;
      font-family: "ali-m";
    }
  }

  .rank-end {
    border-left: none;
  }

  .score {
    position: absolute;
    bottom: -60rpx;
    left: 0;
    transform: translateX(-50%);
    font-size: @font-size-23;
    color: @color-label;
    font-family: "din";
  }
}
</style>
